<?php

namespace app\api\controller;

use app\api\model\PaperStudent;
use app\api\model\PaperStudentList;
use app\common\controller\Api;
use think\Db;
use Exception;
use fast\Random;
use think\exception\PDOException;

/**
 * 分析
 */
class Analyze extends Api
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    //分析报告页列表
    public function analyzeList()
    {
        if (!$this->request->isPost()) $this->error('请求方式错误');
        $grade_id = $this->request->post('grade_id');
        $month = $this->request->post('month');
        $status = $this->request->post('status');
        $name = $this->request->post('name');
        $page = $this->request->post('page', 1);
        $pagesize = $this->request->post('pagesize', 10);
        $school_id = $this->school_id ?? 2;
        //, 'status' => 5
        $list = db('exams')
            ->where(['school_ids' => $school_id, 'status' => 5])
            ->where(function ($query) use ($grade_id) {
                if ($grade_id) {
                    $query->where('grade_id', $grade_id);
                }
            })
            ->where(function ($query) use ($status) {
                if (in_array($status, [1, 2])) {
                    $query->where(['range_id' => $status]);
                }
            })
            ->where(function ($query) use ($month) {
                if ($month) {
                    $query->where('FROM_UNIXTIME(starttime,"%Y-%m")="' . $month . '"');
                }
            })
            ->where(function ($query) use ($name) {
                if ($name) {
                    $query->where('name', 'like', '%' . $name . '%');
                }
            })
            ->paginate($pagesize, false)->each(function ($item, $index) {
                $item['starttime_year'] = date('Y', $item['starttime']);
                $item['starttime_month'] = date('m-d', $item['starttime']);

                //年级
                $item['gradeName'] = db('school_grade')->where(['id' => $item['grade_id']])->value('name');
                //科目
                $item['listnum'] = db('exam_list')->where(['exams_id' => $item['id']])->count();
                //满分
                $item['sumscore'] = db('exam_paper_question')->where(['exams_id' => $item['id']])->sum('zscore');
                return $item;
            });
        $this->success('分析报告页列表', $list);
    }


    //查看分析页
    public function lookAnalyze()
    {
        if (!$this->request->isPost()) $this->error('请求方式错误');
        $id = $this->request->post('id');
        if (!$id) $this->error('未知参数！');
        $info = db('exams')->where('id', $id)->find();
        if (!$info) $this->error('未找到相关考试信息！');
        $data = [];
        //学科数
        $paperCount = db('exam_list')->where(['exams_id' => $info['id']])->count();
        //班级数
        $classCount = db('school_class')->where('id','in', $info['class_ids'])->count();
        //考生数
        $studentCount = db('student')->where('class_id','in', $info['class_ids'])->count();
        //考试总分
        $examTotalScore = db('exam_paper_question')->where(['exams_id' => $info['id']])->sum('zscore');
        //总分排名列表
        $paiming = db('exam_paper_student')->where(['exams_id' => $info['id']])->field('id,class_id,student_name,exam_number,stu_number,totalscore,schoolrank')->order('totalscore desc')->limit(10)->select();
        foreach ($paiming as &$pai) {
            $pai['className'] = db('school_class')->where('id', $pai['class_id'])->value('name');
        }
        //校级分析报告
        //统分区间
        $section = getBonus($examTotalScore);
        $maxList = [];
        $schoolCount = [];
        foreach ($section as $key => $value) {
            $maxList[] = max($value);
            $schoolCount[] = db('exam_paper_student')->where(['exams_id' => $info['id']])->whereBetween('totalscore', $value)->count();
        }
        $schoolList = [
            'score' => $maxList,
            'schoolCount' => $schoolCount,
        ];
        //学科分析报告
        $subjectList = [];
        //学科知识点
        $knowledges = [];
        //学科
        $subjectIds = db('exam_list')->where(['exams_id' => $info['id']])->column('subject_id');
        $subject = db('subject')->where('id', 'in', $subjectIds)->field('id,name')->select();
        //每科平均分
        foreach ($subject as $key => $value) {
            $subjectTotalScore = db('exam_paper_student_list')->where(['exams_id' => $info['id'], 'subject_id' => $value['id']])->sum('totalscore');
            $average = bcdiv($subjectTotalScore, $studentCount, 2);
            $value['average'] = $average;
            $subjectList[$value['name']] = $average;
            $knowledges[$key]['name'] = $value['name'];
            $knowledges[$key]['value'] = rand(1, 20);
        }

        //命题质量分析报告
        $mingTi = [];
        $exam_list = db('exam_list')->where(['exams_id' => $info['id'], 'status' => 5])->select();
        
        foreach ($exam_list as $exam) {
            //单科总分
            $subjectTotalScore = db('exam_paper_student_list')->where(['exams_id' => $info['id'], 'subject_id' => $exam['subject_id']])->sum('totalscore');
            //单科平均分
            $average = bcdiv($subjectTotalScore, $studentCount, 2);
            //难度系数 = 平均分/满分
            //单科满分
            $maxScore = db('exam_paper_question')->where(['exams_list_id' => $exam['id']])->sum('zscore');
            $nandu = round($average / $maxScore, 1);
            //标准差
            $stdev = 0;
            //差异系数 = 标准差／平均数
            $chayixishu = 0;
            //中位数
            $medianNum = 0;
            //众数
            $modeNum = 0;
            $studentScore = db('exam_paper_student_list')->where(['exams_id' => $info['id'], 'subject_id' => $exam['subject_id']])->column('totalscore');

            if (count($studentScore) > 0) {
                $stdev = getStandardDeviation($studentScore);
                $medianNum = getMedian($studentScore);
                $modeNum = getMode($studentScore);
            }

            if ($stdev > 0) {
                $chayixishu = round($stdev / $average, 2);
            }
            $subjectName = db('subject')->where(['id' => $exam['subject_id']])->value('name');
            $mingTi[] = [
                'subjectName' => $subjectName, //学科名称
                'nandu' => $nandu, //难度
                'average' => $average, //平均
                'stdev' => $stdev, //标准差
                'chayixishu' => $chayixishu, //差异系数
                'medianNum' => $medianNum, //中位数
                'modeNum' => $modeNum //众数
            ];
        }
        
        //班级分析报告
        $classBao = [];
        $groups = db('exam_paper_student')->where(['exams_id' => $info['id']])->group('class_id')->select();
        foreach ($groups as $group) {
            //班级名称
            $className = db('school_class')->where('id', $group['class_id'])->value('name');
            //班级总分
            $classTotalScore = db('exam_paper_student')->where('class_id', $group['class_id'])->sum('totalscore');
            //班级学生总数
            $classStudentCount = db('student')->where(['class_id' => $group['class_id']])->count();
            //班级平均分
            $classAverage = 0;
            if ($classStudentCount > 0) {
                $classAverage = round($classTotalScore / $classStudentCount, 2);
            }
            
            $classBao[$className] = $classAverage;
        }

        $data = [
            'paperCount' => $paperCount, //学科数
            'classCount' => $classCount, //班级数
            'studentCount' => $studentCount, //考生数
            'paiming' => $paiming, //总分排名列表
            'schoolList' => $schoolList, //校级分析报告
            'subjectList' => $subjectList, //学科分析报告
            'mingTi' => $mingTi, //命题质量分析报告
            'classBao' => $classBao, //班级分析报告
            'knowledges' => $knowledges //学科知识点
        ];
        $this->success('查看分析页', $data);
    }


    //学科
    public function subjectList()
    {
        if (!$this->request->isPost()) $this->error('请求方式错误');
        $id = $this->request->post('id');
        if (!$id) $this->error('未知参数！');
        $info = db('exams')->where('id', $id)->find();
        if (!$info) $this->error('未找到相关考试信息！');
        //科目
        $subjectIds = db('exam_list')->where(['exams_id'=>$id,'status'=>5])->column('subject_id');
        $subjectLists = db('subject')->where('id', 'in', $subjectIds)->field('id,name')->select();
        $this->success('学科', $subjectLists);
    }

    //班级
    public function classList()
    {
        if (!$this->request->isPost()) $this->error('请求方式错误');
        $id = $this->request->post('id');
        if (!$id) $this->error('未知参数！');
        $info = db('exams')->where('id', $id)->find();
        if (!$info) $this->error('未找到相关考试信息！');
        $examListIds = db('exam_list')->where(['exams_id'=>$id,'status'=>5])->column('id');
        $examListIds = array_unique($examListIds);
        $classIds = db('exam_paper_images')->where('exams_list_id','in',$examListIds)->column('class_id');
        $classIds = array_unique($classIds);
        //班级
        $classList = db('school_class')
        ->where(function($query) use ($classIds){
            if ($classIds) {
                $query->where('id','in',$classIds);
            }
        })
        ->where(['school_id' => $info['school_ids'], 'grade_id' => $info['grade_id'], 'type' => 'XZ'])
        ->field('id,name')->select();
        $this->success('班级', $classList);
    }




    //排行榜
    public function getRankList()
    {
        if (!$this->request->isPost()) $this->error('请求方式错误');
        $id = $this->request->post('id');
        $subject_id = $this->request->post('subject_id');
        $class_ids = $this->request->post('class_ids');
        $keyword = $this->request->post('keyword');
        $page = $this->request->post('page');
        $pagesize = $this->request->post('pagesize', 10);
        $order = $this->request->post('order');
        if (!$id || !$pagesize) $this->error('未知参数！');
        $info = db('exams')->where('id', $id)->find();
        if (!$info) $this->error('未找到相关考试信息！');
        $wheres = [];
        if (!$subject_id) {
            $model = "exam_paper_student";
        } else {
            $examList = db('exam_list')->where(['exams_id' => $info['id'],'subject_id'=>$subject_id])->find();
            $model = "exam_paper_student_list";
            $wheres['exams_list_id'] = $examList['id'];
        }

        $list = db($model)
            ->where(['exams_id' => $info['id']])
            ->where($wheres)
            ->where('class_id', 'in', $class_ids)
            ->where(function ($query) use ($keyword) {
                if ($keyword) {
                    $query->where('student_name|stu_number|exam_number', 'like', '%' . $keyword . '%');
                }
            })
            ->field('id,exams_id,student_id,class_id,subject_id,student_name,stu_number,exam_number')
            ->order($order)
            ->paginate($pagesize, false)->each(function ($item, $index) use ($subject_id) {
                $item['className'] = db('school_class')->where('id', $item['class_id'])->value('name');
                $subjects = [];
                //总分
                $totalScore = db('exam_paper_student')->where(['exams_id'=>$item['exams_id'],'student_id' => $item['student_id']])->field('totalscore,schoolrank,classrank')->find();
                if ($totalScore) {
                    $totalScore['subjectName'] = '总分';
                    array_push($subjects, $totalScore);
                }
                if (!$subject_id) {
                    $subjectIds = db('exam_list')->where(['exams_id'=>$item['exams_id'],'status'=>5])->column('subject_id');
                    $subjectLists = db('subject')->where('id', 'in', $subjectIds)->field('id,name')->select();
                    //单科分数
                    foreach ($subjectLists as $idss) {
                        $subjectList = db('exam_paper_student_list')->where(['exams_id'=>$item['exams_id'],'student_id' => $item['student_id'], 'subject_id' => $idss['id']])->field('totalscore,schoolrank,classrank')->find();
                        if ($subjectList) {
                            $subjectList['subjectName'] = $idss['name'];
                            array_push($subjects, $subjectList);
                        }else{
                            $push = [
                                'totalscore'=> '', 
                                'schoolrank'=> '', 
                                'classrank'=> '', 
                                'subjectName'=> $idss['name']
                             ];
                             array_push($subjects, $push);
                        }
                    }
                    
                } else {
                     //单科分数
                    $subjectList = db('exam_paper_student_list')->where(['exams_id'=>$item['exams_id'],'student_id' => $item['student_id'], 'subject_id' => $subject_id])->field('totalscore,schoolrank,classrank')->find();
                    if ($subjectList) {
                        $subjectList['subjectName'] = db('subject')->where(['id' => $subject_id])->value('name');
                        array_push($subjects, $subjectList);
                    }
                }
                $item['subjects'] = $subjects;
                return $item;
            });

        $this->success('排行榜', $list);
    }


    //小分
    public function getSmallList()
    {
        if (!$this->request->isPost()) $this->error('请求方式错误');
        $id = $this->request->post('id');
        $subject_id = $this->request->post('subject_id');
        $class_ids = $this->request->post('class_ids');
        $keyword = $this->request->post('keyword');
        $page = $this->request->post('page');
        $pagesize = $this->request->post('pagesize', 10);
        // $order = $this->request->post('order','totalscore desc');
        if (!$id || !$subject_id || !$pagesize) $this->error('未知参数！');
        $info = db('exams')->where('id', $id)->find();
        if (!$info) $this->error('未找到相关考试信息！');

        $list = db('exam_paper_student_list')
            ->where(['exams_id' => $info['id'], 'subject_id' => $subject_id])
            ->where('class_id', 'in', $class_ids)
            ->where(function ($query) use ($keyword) {
                if ($keyword) {
                    $query->where('student_name|stu_number|exam_number', 'like', '%' . $keyword . '%');
                }
            })
            ->field('id,exams_list_id,student_id,subject_id,class_id,student_name,stu_number,exam_number,kscoresum,zscoresum,totalscore,schoolrank,classrank')
            // ->order($order)
            ->paginate($pagesize, false)->each(function ($item, $index) {
                $item['className'] = db('school_class')->where('id', $item['class_id'])->value('name');
                //客观题结构
                $kanswerList = db('exam_paper_question_list')->where(['exams_list_id'=>$item['exams_list_id'],'type'=>'KG'])->field('name,key')->select();
                
                //客观题得分
                $kanswerresult = db('exam_paper_images')->where(['exams_list_id' => $item['exams_list_id'], 'student_id' => $item['student_id'], 'page' => 1])->value('kanswerresult');
                if ($kanswerresult) {
                    $kanswerresult = json_decode($kanswerresult, true);
                    foreach ($kanswerresult as $kgs) {
                        foreach ($kanswerList as &$kgz) {
                            if($kgz['key'] === $kgs['key']){
                                $kgz['answer'] = $kgs['answer'];
                                $kgz['score'] = $kgs['score'];
                            }
                            
                        }
                    }
                    $kanswerresult = $kanswerList;
                }else{
                    foreach ($kanswerList as &$kg) {
                        $kg['answer'] = '';
                        $kg['score'] = '';
                    }
                    $kanswerresult = $kanswerList;
                }
                //主观题结构（按题块）
                //主观题得分
                $distinguish = [];
                $blockList = db('exam_paper_block')->where(['exams_list_id'=>$item['exams_list_id']])->field('id,params')->select();
                if ($blockList) {
                    foreach ($blockList as $block) {
                        $params = json_decode($block['params'], true);
                        $distinguishs = db('exam_teacher_make_log')->where(['exams_list_id' => $item['exams_list_id'], 'student_id' => $item['student_id'],'block_id'=>$block['id']])->value('distinguish');
                        if ($distinguishs) {
                            $distinguishs = json_decode($distinguishs, true);
                            foreach ($distinguishs as $val) {
                                foreach ($params as $param) {
                                    foreach ($param['son'] as $son) {
                                        if(isset($son['type']) && $son['type'] === 'merge'){
                                            $push = [
                                                'name' => $val['name'],
                                                'key' => '',
                                                'mark' => $val['mark'],
                                            ];
                                            array_push($distinguish, $push);
                                        }else{
                                            if($val['key'] === $son['key']){
                                                $push = [
                                                    'name' => $son['name'],
                                                    'key' => $son['key']??'',
                                                    'mark' => $val['mark'],
                                                ];
                                                array_push($distinguish, $push);
                                            }
                                        }
                                        
                                    }
                                    
                                    
                                }
                            }
                        }else{
                            foreach ($params as $param) {
                                foreach ($param['son'] as $son) {
                                    if(isset($son['type']) && $son['type'] === 'merge'){
                                        $push = [
                                            'name' => $son['name'],
                                            'key' => '',
                                            'mark' => '',
                                        ];
                                    }else{
                                        $push = [
                                            'name' => $son['name'],
                                            'key' => $son['key'],
                                            'mark' => '',
                                        ];
                                    }
                                    
                                    array_push($distinguish, $push);
                                } 
                            }
                            
                        }
                        
                        
                    }
    
                }
                
                $item['kanswerresult'] = $kanswerresult;
                $item['distinguish'] = $distinguish;
                return $item;
            });

        $this->success('小分', $list);
    }

    //班分对比配置参数
    public function getCfgList()
    {
        if (!$this->request->isGet()) $this->error('请求方式错误');
        $list = db('cfg')->where(['status' => 1])->field('id,type')->select();
        $this->success('班分对比配置参数', $list);
    }

    //配置参数详情
    public function getCfg()
    {
        if (!$this->request->isPost()) $this->error('请求方式错误');
        $id = $this->request->post('id');
        if (!$id) $this->error('未知参数！');
        $info = db('cfg')->where(['id' => $id])->field('multiplejson')->find();
        if ($info) {
            $info['multiplejson'] = json_decode($info['multiplejson'], true);
        }
        $this->success('班分对比配置参数', $info['multiplejson']);
    }

    //编辑配置参数详情
    public function editCfg()
    {
        if (!$this->request->isPost()) $this->error('请求方式错误');
        $id = $this->request->post('id');
        $multiplejson = $this->request->post('multiplejson/a');
        if (!$id) $this->error('未知参数！');
        if (!is_array($multiplejson)) $this->error('未知参数！');
        $info = db('cfg')->where(['id' => $id])->find();
        if (!$info) $this->error('未找到相关信息！');
        $up = db('cfg')->where('id', $id)->update([
            'multiplejson' => json_encode($multiplejson)
        ]);
        if (!$up) $this->error('操作失败！');
        $this->success('操作成功！');
    }


    //班分对比
    public function classScoreList()
    {
        if (!$this->request->isPost()) $this->error('请求方式错误');
        $id = $this->request->post('id');
        $cfgid = $this->request->post('cfg');
        $subject_id = $this->request->post('subject_id');
        $class_ids = $this->request->post('class_ids');
        if (!$id || !$cfgid) $this->error('未知参数！');
        $info = db('exams')->where('id', $id)->find();
        if (!$info) $this->error('未找到相关考试信息！');

        $list = [];
        //配置参数
        $cfg = db('cfg')->where(['id' => $cfgid])->field('multiplejson')->find();
        if ($cfg) {
            $cfg['multiplejson'] = json_decode($cfg['multiplejson'], true);
        }
        $multiplejson = $cfg['multiplejson'];
        $where['exams_id'] = $id;
        if (!$subject_id) {
            #总分
            if (!$class_ids) {
                #全体
                
                $schoolTotal = PaperStudent::getClassArray($where, $multiplejson);
                if ($schoolTotal) {
                    array_push($list, $schoolTotal);
                }
            } else {
                #全体
                $schoolTotal = PaperStudent::getClassArray($where, $multiplejson);
                if ($schoolTotal) {
                    array_push($list, $schoolTotal);
                }
                $classArray = explode(',', $class_ids);
                foreach ($classArray as $value) {
                    $where['class_id'] = $value;
                    $classTotal = PaperStudent::getClassArray($where, $multiplejson, 1);
                    if ($classTotal) {
                        array_push($list, $classTotal);
                    }
                }
            }
        } else {
            #单科
            $where['subject_id'] = $subject_id;
            if (!$class_ids) {
                #全体
                $schoolTotal = PaperStudentList::getClassArray($where);
                if ($schoolTotal) {
                    array_push($list, $schoolTotal);
                }
            } else {
                #全体
                $schoolTotal = PaperStudentList::getClassArray($where, $multiplejson);
                if ($schoolTotal) {
                    array_push($list, $schoolTotal);
                }

                $classArray = explode(',', $class_ids);
                foreach ($classArray as $value) {
                    $where['class_id'] = $value;
                    $classTotal = PaperStudentList::getClassArray($where, $multiplejson, 1);
                    if ($classTotal) {
                        array_push($list, $classTotal);
                    }
                }
            }
        }
        $classList = [];
        foreach ($list as $key => $value) {
            if ($value['className'] != "学校全体") {
                $classList[] = $value;
                unset($list[$key]);
            }
        }
        $classList = arraySort($classList, 'averageScore');
        foreach ($classList as $num => &$class) {
            $class['averageRank'] = $num + 1;
        }
        $classList = arraySort($classList, 'multipleRate');
        foreach ($classList as $num => &$class) {
            $class['multipleRank'] = $num + 1;
        }
       
        $rates = $this->setRateRank($classList, $cfgid);
        $list = array_merge($list, $rates);
        $data = [
            'cfg' => $cfg,
            'list' => $list
        ];


        $this->success('班分对比', $data);
    }

    //三率排名
    public function setRateRank($array, $cfgId)
    {
        $cfg = db('cfg')->where(['id' => $cfgId])->find();
        if ($cfg) {
            $cfg['multiplejson'] = json_decode($cfg['multiplejson'], true);
        }
        $multiplejson = $cfg['multiplejson'];
        $high = [];
        $excellence = [];
        $good = [];
        $pass = [];
        $low = [];
        switch ($cfg['type']) {
            case '3档':
                foreach ($array as $key => $value) {
                    foreach ($value['rates'] as $k => $val) {
                        switch ($val['name']) {

                            case '优秀':
                                $excellence[] = [
                                    'className' => $value['className'],
                                    'num' => intval($val['num']),
                                    'rank' => null
                                ];
                                break;
                            case '良好':
                                $good[] = [
                                    'className' => $value['className'],
                                    'num' => intval($val['num']),
                                    'rank' => null
                                ];
                                break;
                            case '及格':
                                $pass[] = [
                                    'className' => $value['className'],
                                    'num' => intval($val['num']),
                                    'rank' => null
                                ];
                                break;
                        }
                    }
                }
                break;
            case '4档':
                foreach ($array as $key => $value) {
                    foreach ($value['rates'] as $k => $val) {

                        switch ($val['name']) {

                            case '优秀':
                                $excellence[] = [
                                    'className' => $value['className'],
                                    'num' => intval($val['num']),
                                    'rank' => null
                                ];
                                break;
                            case '良好':
                                $good[] = [
                                    'className' => $value['className'],
                                    'num' => intval($val['num']),
                                    'rank' => null
                                ];
                                break;
                            case '及格':
                                $pass[] = [
                                    'className' => $value['className'],
                                    'num' => intval($val['num']),
                                    'rank' => null
                                ];
                                break;
                            case '低分':
                                $low[] = [
                                    'className' => $value['className'],
                                    'num' => intval($val['num']),
                                    'rank' => null
                                ];
                                break;
                        }
                    }
                }
                break;
            case '5档':
                foreach ($array as $key => $value) {
                    foreach ($value['rates'] as $k => $val) {
                        switch ($val['name']) {
                            case '高分':
                                $high[] = [
                                    'className' => $value['className'],
                                    'num' => intval($val['num']),
                                    'rank' => null
                                ];

                                break;
                            case '优秀':
                                $excellence[] = [
                                    'className' => $value['className'],
                                    'num' => intval($val['num']),
                                    'rank' => null
                                ];
                                break;
                            case '良好':
                                $good[] = [
                                    'className' => $value['className'],
                                    'num' => intval($val['num']),
                                    'rank' => null
                                ];
                                break;
                            case '及格':
                                $pass[] = [
                                    'className' => $value['className'],
                                    'num' => intval($val['num']),
                                    'rank' => null
                                ];
                                break;
                            case '低分':
                                $low[] = [
                                    'className' => $value['className'],
                                    'num' => intval($val['num']),
                                    'rank' => null
                                ];
                                break;
                        }
                    }
                }
                break;
        }
        if (!empty($high)) {
            $high = arraySort($high, 'num');
            foreach ($high as $num => &$hig) {
                $hig['rank'] = $num + 1;
                foreach ($array as &$highs) {
                    if ($highs['className'] == $hig['className']) {
                        foreach ($highs['rates'] as &$highList) {
                            if ($highList['name'] === '高分') {
                                $highList['rank'] = $num + 1;
                            }
                        }
                    }
                }
            }
        }
        if (!empty($excellence)) {
            $excellence = arraySort($excellence, 'num');
            foreach ($excellence as $num => &$excel) {
                $excel['rank'] = $num + 1;
                foreach ($array as &$excellences) {
                    if ($excellences['className'] == $excel['className']) {
                        foreach ($excellences['rates'] as &$excellenceList) {
                            if ($excellenceList['name'] === '优秀') {
                                $excellenceList['rank'] = $num + 1;
                            }
                        }
                    }
                }
            }
        }
        if (!empty($good)) {
            $good = arraySort($good, 'num');
            foreach ($good as $num => &$goo) {
                $goo['rank'] = $num + 1;
                foreach ($array as &$goods) {
                    if ($goods['className'] == $goo['className']) {
                        foreach ($goods['rates'] as &$goodList) {
                            if ($goodList['name'] === '良好') {
                                $goodList['rank'] = $num + 1;
                            }
                        }
                    }
                }
            }
        }
        if (!empty($pass)) {
            $pass = arraySort($pass, 'num');
            foreach ($pass as $num => &$pas) {
                $pas['rank'] = $num + 1;
                foreach ($array as &$passs) {
                    if ($passs['className'] == $pas['className']) {
                        foreach ($passs['rates'] as &$passList) {
                            if ($passList['name'] === '及格') {
                                $passList['rank'] = $num + 1;
                            }
                        }
                    }
                }
            }
        }
        if (!empty($low)) {
            $low = arraySort($low, 'num');
            foreach ($low as $num => &$lo) {
                $lo['rank'] = $num + 1;
                foreach ($array as &$lows) {
                    if ($lows['className'] == $lo['className']) {
                        foreach ($lows['rates'] as &$lowList) {
                            if ($lowList['name'] === '低分') {
                                $lowList['rank'] = $num + 1;
                            }
                        }
                    }
                }
            }
        }
        return $array;
    }

    //分段页
    public function sectionPage()
    {
        if (!$this->request->isPost()) $this->error('请求方式错误');
        $id = $this->request->post('id');
        if (!$id) $this->error('未知参数！');
        $info = db('exams')->where('id', $id)->find();
        if (!$info) $this->error('未找到相关考试信息！');
        //考试满分
        $examFullScore = db('exam_paper_question')->where(['exams_id' => $id])->sum('zscore');
        if ($examFullScore < 0) $this->success('分段页', []);
        if ($examFullScore - 0 >= config('site.criterionNum')) {
            $criterionNum = config('site.criterionNum');
        } else {
            $criterionNum = $examFullScore - 0;
        }
        $data = [
            'examFullScore' => $examFullScore,
            'high' => $examFullScore,
            'low' => 0,
            'criterionNum' => $criterionNum
        ];
        $this->success('分段页', $data);
    }

    //分段统计
    public function sectionStatistic()
    {
        if (!$this->request->isPost()) $this->error('请求方式错误');
        $id = $this->request->post('id');
        $type = $this->request->post('type');
        $subject_id = $this->request->post('subject_id');
        $class_ids = $this->request->post('class_ids');
        $criterionNum = $this->request->post('criterionNum');
        $low = $this->request->post('low', 0);
        $high = $this->request->post('high');
        if (!$id || !in_array($type, [0, 1]) || !$high || !$criterionNum) $this->error('未知参数！');
        $info = db('exams')->where('id', $id)->find();
        if (!$info) $this->error('未找到相关考试信息！');

        $list = [];
        //分段基准数
        if (!$criterionNum) {
            if (!$subject_id) {
                $criterionNum = config('site.criterionNum');
            } else {
                $criterionNum = config('site.subCriterionNum');
            }
        }
        $where['exams_id'] = $id;
        if (!$subject_id) {
            #总分
            if (!$class_ids) {
                #全体
                $class = PaperStudent::sectionTotal($where, $criterionNum, $low, $high, $type);
                if ($class) {
                    array_push($list, $class);
                }
            } else {
                #全体
                $class = PaperStudent::sectionTotal($where, $criterionNum, $low, $high, $type);
                if ($class) {
                    array_push($list, $class);
                }
                $classArray = explode(',', $class_ids);
                foreach ($classArray as $value) {
                    $where['class_id'] = $value;
                    $class = PaperStudent::sectionTotal($where, $criterionNum, $low, $high, $type,1);
                    if ($class) {
                        array_push($list, $class);
                    }
                }
            }
        } else {

            #单科
            $where['subject_id'] = $subject_id;
            if (!$class_ids) {
                #全体
                $class = PaperStudentList::sectionTotal($where, $criterionNum, $low, $high, $type,0);
                if ($class) {
                    array_push($list, $class);
                }
            } else {
                
                #全体
                $class = PaperStudentList::sectionTotal($where, $criterionNum, $low, $high, $type,0);
                if ($class) {
                    array_push($list, $class);
                }
                
                $classArray = explode(',', $class_ids);
                foreach ($classArray as $value) {
                    $where['class_id'] = $value;
                    $class = PaperStudentList::sectionTotal($where, $criterionNum, $low, $high, $type,1);
                    if ($class) {
                        array_push($list, $class);
                    }
                }
            }
        }
        $this->success('分段统计', $list);
    }

    //名次和比例参数列表
    public function getAnaSetList()
    {
        if (!$this->request->isPost()) $this->error('请求方式错误');
        $list = db('analyse_set')->where(['status' => 1])->field('id,name,type')->select();
        
        $this->success('名次和比例参数列表', $list);
    }


    //名次和比例参数详情
    public function getAnaSet()
    {
        if (!$this->request->isPost()) $this->error('请求方式错误');
        $id = $this->request->post('id');
        if (!$id) $this->error('未知参数！');
        $info = db('analyse_set')->where(['id' => $id])->find();
        if ($info) {
            $multiplejson = json_decode($info['multiplejson'], true);
            $data = [];
            foreach ($multiplejson as $key => $value) {
                $data[] = $key;
            }
            $info['multiplejson'] = $data;

        }
        $this->success('名次和比例参数详情', $info);
    }

    //编辑名次和比例参数
    public function editAnaSet()
    {
        if (!$this->request->isPost()) $this->error('请求方式错误');
        $id = $this->request->post('id');
        $multiplejson = $this->request->post('multiplejson/a');
        if (!$id) $this->error('未知参数！');
        if (!is_array($multiplejson)) $this->error('未知参数！');
        $info = db('analyse_set')->where(['id' => $id])->find();
        if (!$info) $this->error('未找到相关信息！');
        $data = [];
        foreach ($multiplejson as $key => $value) {
            $data[$value] = '';
        }
        
        $up = db('analyse_set')->where('id', $id)->update([
            'multiplejson' => json_encode($data)
        ]);
        // if (!$up) $this->error('操作失败！');
        $this->success('操作成功');
    }


    //名次和比例分析
    public function rankScale()
    {
        if (!$this->request->isPost()) $this->error('请求方式错误');
        $exams_id = $this->request->post('exams_id');
        $subject_id = $this->request->post('subject_id');
        $class_ids = $this->request->post('class_ids');
        $setId = $this->request->post('setId');
        if (!$setId || !$exams_id) $this->error('未知参数！');
        $where['exams_id'] = $exams_id;
        $list = [];
        if (!$subject_id) {
            #总分
            if (!$class_ids) {
                #全体
                $class = PaperStudent::rankScale($where,$setId);
                if ($class) {
                    array_push($list, $class);
                }
            } else {
                #全体
                $class = PaperStudent::rankScale($where, $setId);
                if ($class) {
                    array_push($list, $class);
                }
                $classArray = explode(',', $class_ids);
                foreach ($classArray as $value) {
                    $where['class_id'] = $value;
                    $class = PaperStudent::rankScale($where, $setId,1);
                    if ($class) {
                        array_push($list, $class);
                    }
                }
            }
        } else {
            #单科
            $where['subject_id'] = $subject_id;
            if (!$class_ids) {
                #全体
                $class = PaperStudentList::rankScale($where, $setId);
                if ($class) {
                    array_push($list, $class);
                }
            } else {
                #全体
                $class = PaperStudentList::rankScale($where, $setId);
                if ($class) {
                    array_push($list, $class);
                }

                $classArray = explode(',', $class_ids);
                foreach ($classArray as $value) {
                    $where['class_id'] = $value;
                    $class = PaperStudentList::rankScale($where, $setId,1);
                    if ($class) {
                        array_push($list, $class);
                    }
                }
            }
        }
        $this->success('名次和比例分析', $list);
    }
}
